<?php
/**
 * Created by PhpStorm.
 * User: xaq
 * Date: 2017/5/26
 * Time: 16:46
 */

namespace app\api\controller\v1;

use app\api\controller\BaseController;
use app\api\validate\PageMustBePostiveInt;
use app\lib\exception\QuestionException;
use app\lib\exception\SuccessMessage;
use app\api\validate\QuestionValidate;
use app\api\service\Token as TokenService;
use app\api\model\User as UserModel;
use app\api\model\Question as QuestionModel;
use app\lib\exception\UserException;

class Question extends BaseController
{
    public function SetQuestion() {
        $validate = new QuestionValidate();
        $validate->goCheck();
        //根据token来获取uid
        //根据uid来查找用户数据，判断用户是否存在，如果不存，抛出异常
        //获取用户从客户端提交的问题信息
        //将问题信息和用户uid提交到数据库
        $uid = TokenService::getCurrentUid();
        $user = UserModel::get($uid);
        if(!$user) {
            throw new UserException();
        }
        $dataArray = $validate->getDataByRule(input('post.'));
        $content = $dataArray['content'];
        $name = $dataArray['name'];
        $img_url = $dataArray['img_url'];
        $question = QuestionModel::create([
            'user_id' => $uid,
            'content' => $content,
            'name' => $name,
            'img_url' => $img_url
        ]);
        if(!$question) {
            throw new QuestionException();
        }
        return json(new SuccessMessage(),201);

    }
    //获取问题数组信息
    public function getQuestion($page) {
        (new PageMustBePostiveInt()) ->goCheck();
        $question =QuestionModel::getQuestions($page);
        if(!$question){
            throw new QuestionException([
                'msg' => '获取问题失败，请稍后再试'
            ]);
        }
        return $question;
    }

}